package response

import (
	"github.com/kataras/iris/v12"
)

type Response struct {
	Ctx  iris.Context
	Msg  string
	Data interface{}
	Map  map[string]interface{}
}

func New(ctx iris.Context) *Response {
	return &Response{
		Ctx: ctx,
	}
}

func (r *Response) Set(key string, val interface{}) *Response {
	if r.Map == nil {
		r.Map = make(map[string]interface{})
	}
	r.Map[key] = val
	return r
}

func (r *Response) SetData(data interface{}) *Response {
	r.Data = data
	return r
}

func (r *Response) SetMessage(msg string) *Response {
	r.Msg = msg
	return r
}

func (r *Response) SetMap(mapData map[string]interface{}) *Response {
	r.Map = mapData
	return r
}

func (r *Response) Error() {
	md := iris.Map{
		"code": -1,
	}
	if r.Msg != "" {
		md["msg"] = r.Msg
	}
	if r.Map != nil {
		for key, val := range r.Map {
			md[key] = val
		}
	}
	r.Ctx.JSON(md)
}

func (r *Response) Success() {
	md := iris.Map{
		"code": 0,
	}
	if r.Data != nil {
		md["data"] = r.Data
	}
	if r.Map != nil {
		for key, val := range r.Map {
			md[key] = val
		}
	}
	r.Ctx.JSON(md)
}
